<?php
namespace  app\zyapi\controller;
/**
 * @Author: user
 * @Date:   2019-01-18 13:24:23
 * @Last Modified by:   user
 * @Last Modified time: 2019-01-23 14:08:31
 */
use think\Controller;
use think\Loader;//引入此文件
/**
 * 文件操作类
 */
class FileController extends Controller
{
	//执行构造 进行初始化工作
	function _initialize()
    {
        parent::_initialize();
        Loader::import('PHPExcel', __DIR__."/../lib/zy_file/phpoffice/phpexcel/Classes", '.php');
    }
	/**
	 * @method exportExcel excel导入方法
	 *  @param [string]  $name 文件名  
	 * @param [json]  $data 要导入的数据列表
	 * @param [json] $field 表头字段信息
	 * @example 表头字段  $field=[['id','编号'],['name','昵称']]
	 * @example 数据列表 $data=[['id'=>1,'name'=>'天王'],['id'=>2,'name'=>'盖地虎']]
	 * @return 成功输出cexel文件 错误返回json格式错误信息 
	 * 错误信息说明：
	 * 		001：未定义包含字段的参数数据 field
	 * 		002：未定义需要处理的数据  data
	 * 		003：传递的$data数据格式不合法
	 * 		004：传递的$field数据格式不合法
	 */
	public function exportExcel()
	{
		$data=$this->request->param();
		//dump($data);exit;
		//数据过滤
		if(!isset($data['name']) || empty($data['name'])){
			//未设置文件名时，定义当前时间为文件名
			$data['name']=date('YmdHis',time());
		}
		if(!isset($data['data']) || empty($data['data'])){
			return json(['status'=>'error','message'=>'参数错误(001)：所需的参数值缺失']);
		}
		if(!isset($data['field']) || empty($data['field'])){
			return json(['status'=>'error','message'=>'参数错误(002)：所需的参数值缺失']);
		}
		if(!is_array($data['data'])){
			return json(['status'=>'error','message'=>'参数错误(003)：参数格式不合法']);
		}
		if(!is_array($data['field'])){
			return json(['status'=>'error','message'=>'参数错误(004)：参数格式不合法']);
		}
















/*		//需要导出的数据
		$data['data']=[
			['id'=>1,'name'=>'天王']
			,['id'=>2,'name'=>'盖地虎']
		];
		//表头字段
		$data['field']=array(
			array('id','编号'),
			array('name','昵称')
		);
		//文件名
		$fileName='demo';*/
		//文件名
		//$fileName=$data['name'];
		//表格列标志
		$column=array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
		//设置数据格式 $field=['A'=>['id','编号'],'B'=>['name','姓名']];
		$field=array();
		for ($i=0; $i <count($data['field']) ; $i++) { 
			$field[$column[$i]]=$data['field'];
		}
		$list=$data['data'];

		//dump($this->request->param());exit;
		$fileName='demo';
		   $field = array(
            'A' => array('id', 'ID'),
            'B' => array('name', '用户ID'),
        );
		  $list =[
			['id'=>1,'name'=>'天王']
			,['id'=>2,'name'=>'盖地虎']
		];
		
		//实例化excel类
		$objPHPExcel = new \PHPExcel();
        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel); //设置保存版本格式
        foreach ($list as $key => $value) {
            foreach ($field as $k => $v) {
                if ($key == 0) {
                    $objPHPExcel->getActiveSheet()->setCellValue($k . '1', $v[1]);
                }
                $i = $key+2; //表格是从2开始的
                $objPHPExcel->getActiveSheet()->setCellValue($k . $i, $value[$v[0]]);
            }
        }

        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename='.$fileName.'.xls');
        header("Content-Transfer-Encoding:binary");
		//$objWriter->save($fileName.'.xls');
    	$objWriter->save('php://output');exit;
        //return json(['status'=>'success','message'=>'数据导出成功']);
	}

/**
 * 请求api demo
 * @return [type] [description]
 */
	public function requestDemo(){
		//需要导出的数据
		$data=[['id'=>1,'name'=>'天王'],['id'=>2,'name'=>'盖地虎']];
		//表头字段
		$field=[['id','编号'],['name','昵称']];
		//文件名
		$name='demo';

		//发起请求
		$data=['data'=>$data,'field'=>$field,'name'=>$name];
		$data = http_build_query($data);   

		$url="http://oa.300c.cn/zyapi/file/exportExcel";//?".$data;
		//$result = file_get_contents($url);
		$ch = curl_init(); 
		curl_setopt ($ch, CURLOPT_URL, $url); 
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10); 
		$dxycontent = curl_exec($ch); 
		curl_close($ch);
		$path = "demo.pdf";
		$ret  = file_put_contents($path, $arr['data']);
		if ($ret) {
		    echo '保存成功'; // 然后可以取查看文件
		}
		echo $dxycontent;
	}


	    // 发送请求

		

	//exportExcelAsArray导出
	public function exportExcel2()
	{
		//需要导出的数据
		$data=[['id'=>1,'name'=>'天王'],['id'=>2,'name'=>'盖地虎']];
		//表头字段
		$field=[['id','编号'],['name','昵称']];
		//文件名
		$name='demo';
		$expCellName=$field;
		$expTableData=$data;
        //include_once EXTEND_PATH.'PHPExcel/PHPExcel.php';//方法二
       // $xlsTitle = iconv('utf-8', 'gb2312', $data['name']);//文件名称
        $fileName = $name.date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        $objPHPExcel = new \PHPExcel();//方法一
        //$objPHPExcel = new \PHPExcel();//方法二
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $fileName.'  Export time:'.date('Y-m-d H:i:s'));
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);
        }
        // Miscellaneous glyphs, UTF-8
        for($i=0;$i<$dataNum;$i++){
            for($j=0;$j<$cellNum;$j++){
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
            }
        }
        ob_end_clean();//这一步非常关键，用来清除缓冲区防止导出的excel乱码
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$fileName.'.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//"xls"参考下一条备注
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');//"Excel2007"生成2007版本的xlsx，"Excel5"生成2003版本的xls
        $objWriter->save('php://output');
        //$objWriter->save('demo.xls');
        exit;
	}


}
